<script setup lang="ts">
import { computed, reactive, ref } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';

import { todoItemsInfo, todoItemsUpdate } from '#/api/hm/todoItems';
import { Description, useDescription } from '#/components/description';

import { descSchema } from '../info';

const { hasAccessByRoles } = useAccess();
const isDirector = computed(() => {
  return hasAccessByRoles(['dept-manage']);
});
const isShopOwner = computed(() => {
  return hasAccessByRoles(['shop-owner']);
});
const isCeo = computed(() => {
  return hasAccessByRoles(['ceo']);
});
const [BasicModal, modalApi] = useVbenModal({
  draggable: true,
  onOpenChange: handleOpenChange,
});
const [registerDescription, { setDescProps }] = useDescription({
  column: 2,
  labelStyle: {
    minWidth: '150px',
    width: '150px',
  },
  schema: descSchema,
});
const leader = ref(false);
const todoType = ref('');
// 店长评分
const managerRating = ref<number | undefined>();
// 店长评语
const managerEvaluation = ref<string | undefined>();
// 总监评分
const directorRating = ref<number | undefined>();
// 总监评语
const directorEvaluation = ref<string | undefined>();
// 总经理评分
const ceoRating = ref<number | undefined>();
// 总经理评语
const ceoEvaluation = ref<string | undefined>();

async function handleOpenChange(open: boolean) {
  if (!open) {
    return null;
  }
  modalApi.modalLoading(true);

  const { id } = modalApi.getData() as { id: number | string };
  const { isLeader } = modalApi.getData() as { isLeader: boolean };
  leader.value = isLeader;
  const record = await todoItemsInfo(id);
  todoType.value = record.todoType;
  managerRating.value = record.managerRating;
  managerEvaluation.value = record.managerEvaluation;
  directorRating.value = record.directorRating;
  directorEvaluation.value = record.directorEvaluation;
  ceoRating.value = record.ceoRating;
  ceoEvaluation.value = record.ceoEvaluation;
  console.log('record', record);
  console.log('todoType', todoType.value);
  // 赋值
  setDescProps({ data: record });

  modalApi.modalLoading(false);
}

// 编辑状态管理
const isEditing = reactive({
  store: false,
  director: false,
  general: false,
});

// 临时存储编辑数据
const tempStoreRate = ref<number | undefined>();
const tempStoreComment = ref<string | undefined>();
// 同理定义 tempDirector... / tempGeneral...

// 切换编辑状态
const toggleEdit = (type: 'director' | 'general' | 'store') => {
  const types = {
    store: () => {
      tempStoreRate.value = managerRating.value;
      tempStoreComment.value = managerEvaluation.value;
      isEditing.store = !isEditing.store;
    },
    director: () => {
      tempStoreRate.value = directorRating.value;
      tempStoreComment.value = directorEvaluation.value;
      isEditing.director = !isEditing.director;
    },
    general: () => {
      tempStoreRate.value = ceoRating.value;
      tempStoreComment.value = ceoEvaluation.value;
      isEditing.general = !isEditing.general;
    },
  };
  types[type]?.();
};

// 提交处理
const handleSubmit = async (type: 'director' | 'general' | 'store') => {
  try {
    // 更新本地数据
    switch (type) {
      case 'director': {
        directorRating.value = tempStoreRate.value;
        directorEvaluation.value = tempStoreComment.value;
        break;
      }
      case 'general': {
        ceoRating.value = tempStoreRate.value;
        ceoEvaluation.value = tempStoreComment.value;
        break;
      }
      case 'store': {
        managerRating.value = tempStoreRate.value;
        managerEvaluation.value = tempStoreComment.value;
        break;
      }
    }
    const params = {
      todoId: modalApi.getData().id,
      managerRating: managerRating.value,
      managerEvaluation: managerEvaluation.value,
      directorRating: directorRating.value,
      directorEvaluation: directorEvaluation.value,
      ceoRating: ceoRating.value,
      ceoEvaluation: ceoEvaluation.value,
    };
    await todoItemsUpdate(params);
    // message.success('评价成功');
    isEditing[type] = false;
  } catch (error) {
    console.error('提交失败', error);
  }
};
</script>

<template>
  <BasicModal
    :footer="false"
    :fullscreen-button="false"
    title="待办详情"
    class="w-[1000px]"
  >
    <Description @register="registerDescription" />
    <div v-if="todoType === '0'">
      <a-divider orientation="left">领导评价</a-divider>
      <a-row :gutter="16">
        <!-- 店长评价卡片 -->
        <a-col :span="8">
          <a-card title="店长评价" :bordered="false">
            <template #extra v-if="leader && isShopOwner">
              <a-button @click="toggleEdit('store')" size="small">
                {{ isEditing.store ? '取消' : '编辑' }}
              </a-button>
            </template>

            <div v-if="!isEditing.store">
              <p>评分：</p>
              <a-rate :value="managerRating" disabled />
              <p>评语：</p>
              <p>{{ managerEvaluation }}</p>
            </div>

            <a-form v-else @finish="handleSubmit('store')">
              <a-form-item label="评分">
                <a-rate v-model:value="tempStoreRate" />
              </a-form-item>
              <a-form-item label="评语">
                <a-textarea v-model:value="tempStoreComment" />
              </a-form-item>
              <a-button
                type="primary"
                html-type="submit"
                @click="handleSubmit('store')"
              >
                保存
              </a-button>
            </a-form>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card title="总监评价" :bordered="false">
            <template #extra v-if="leader && isDirector">
              <a-button @click="toggleEdit('director')" size="small">
                {{ isEditing.director ? '取消' : '编辑' }}
              </a-button>
            </template>

            <div v-if="!isEditing.director">
              <p>评分：</p>
              <a-rate :value="directorRating" disabled />
              <p>评语：</p>
              <p>{{ directorEvaluation }}</p>
            </div>

            <a-form v-else @finish="handleSubmit('director')">
              <a-form-item label="评分">
                <a-rate v-model:value="tempStoreRate" />
              </a-form-item>
              <a-form-item label="评语">
                <a-textarea v-model:value="tempStoreComment" />
              </a-form-item>
              <a-button
                type="primary"
                html-type="submit"
                @click="handleSubmit('director')"
              >
                保存
              </a-button>
            </a-form>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card title="总经理评价" :bordered="false">
            <template #extra v-if="leader && isCeo">
              <a-button @click="toggleEdit('general')" size="small">
                {{ isEditing.general ? '取消' : '编辑' }}
              </a-button>
            </template>

            <div v-if="!isEditing.general">
              <p>评分：</p>
              <a-rate :value="ceoRating" disabled />
              <p>评语：</p>
              <p>{{ ceoEvaluation }}</p>
            </div>

            <a-form v-else @finish="handleSubmit('general')">
              <a-form-item label="评分">
                <a-rate v-model:value="tempStoreRate" />
              </a-form-item>
              <a-form-item label="评语">
                <a-textarea v-model:value="tempStoreComment" />
              </a-form-item>
              <a-button
                type="primary"
                html-type="submit"
                @click="handleSubmit('general')"
              >
                保存
              </a-button>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </BasicModal>
</template>
